﻿using System;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Configuration;
using System.Web.Security;
using System.Data;

public partial class Login : System.Web.UI.Page
{
    SqlConnection conn;
    SqlCommand cmd;
    SqlDataReader dr;
    string DecPass = string.Empty;
    bool PasswordChange;
    protected void Page_Init(object sender, EventArgs e)
    {
        conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["connstr"].ConnectionString);
        EstablishConnection(conn);
        LoginControl.FindControl("UserName").Focus();
        Session.RemoveAll();
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.QueryString["Msg"] != null)
        {
            ltMessage.Text = Request.QueryString["Msg"];
        }
    }
    void EstablishConnection(SqlConnection conn)
    {
        try
        {
            conn.Open();
        }
        catch (SqlException ex)
        {
            ltMessage.Mode = LiteralMode.Transform;
            ltMessage.Text = ex.Message;
        }
    }
    protected void UpdateLastLogin(string UserName)
    {
        cmd = new SqlCommand("Update HAT_UserAccounts set LastLogin=@LastLogin where UserName=@UserName", conn);
        cmd.Parameters.Add("@LastLogin", SqlDbType.DateTime).Value = DateTime.Now;
        cmd.Parameters.Add("@UserName", SqlDbType.VarChar).Value = LoginControl.UserName.ToString();
        try
        {
            cmd.ExecuteNonQuery();
        }
        catch (SqlException ex)
        {
            ltMessage.Text = ex.Message;
        }
    }
    private bool CheckPasswordChange(string UserName)
    {
        cmd = new SqlCommand("select ForcedPasswordChange from HAT_UserAccounts where UserName=@UName", conn);
        cmd.Parameters.Add("@UName", SqlDbType.VarChar).Value = UserName;
        try
        {
            dr = cmd.ExecuteReader();
            if (dr.HasRows)
            {
                while (dr.Read())
                {
                    PasswordChange = dr.GetBoolean(0);
                }
                dr.Close();
            }
            else
            {
                return false;
            }
        }
        catch (SqlException ex)
        {
            ltMessage.Text = ex.Message;
        }
        return PasswordChange;
    }
    protected void AuthenticateLogin(object sender, AuthenticateEventArgs e)
    {
        DecPass = RetreiveUserPassword(LoginControl.UserName);
        PasswordChange = CheckPasswordChange(LoginControl.UserName);
        if (PasswordChange)
        {
            try
            {
                if (LoginControl.Password.Equals(DecPass))
                {
                    UpdateLastLogin(LoginControl.UserName);
                    FormsAuthenticationTicket tkt = new FormsAuthenticationTicket(1, LoginControl.UserName, DateTime.Now, DateTime.Now.AddMinutes(5), LoginControl.RememberMeSet, FormsAuthentication.FormsCookiePath);
                    string hashCook = FormsAuthentication.Encrypt(tkt);
                    HttpCookie cook = new HttpCookie(FormsAuthentication.FormsCookieName, hashCook);
                    e.Authenticated = true;
                    Session["LoggedInUser"] = LoginControl.UserName;
                    Page.Response.Redirect("~/ChangePassword.aspx", true);
                }
                else
                {
                    e.Authenticated = false;
                }
            }
            catch (SqlException ex)
            {
                ltMessage.Text = ex.Message;
            }
        }
        else
        {
            try
            {
                if (LoginControl.Password.Equals(DecPass))
                {
                    UpdateLastLogin(LoginControl.UserName);
                    FormsAuthenticationTicket tkt = new FormsAuthenticationTicket(1, LoginControl.UserName, DateTime.Now, DateTime.Now.AddMinutes(5), LoginControl.RememberMeSet, FormsAuthentication.FormsCookiePath);
                    string hashCook = FormsAuthentication.Encrypt(tkt);
                    HttpCookie cook = new HttpCookie(FormsAuthentication.FormsCookieName, hashCook);
                    e.Authenticated = true;
                    FormsAuthentication.RedirectFromLoginPage(LoginControl.UserName, LoginControl.RememberMeSet);
                }
                else
                {
                    e.Authenticated = false;
                }
            }
            catch (SqlException ex)
            {
                ltMessage.Text = ex.Message;
            }

        }
    }
    private string RetreiveUserPassword(string UserName)
    {
        string TmpPass = string.Empty;
        cmd = new SqlCommand("Select Password, UserID from HAT_UserAccounts where UserName=@User and IsApproved='1'", conn);
        cmd.Parameters.Add("@User", SqlDbType.VarChar).Value = UserName;
        try
        {
            dr = cmd.ExecuteReader();
            while (dr.Read())
            {
                TmpPass = dr.GetString(0);
                Session["UserID"] = dr.GetInt32(1);
                Session["UserRole"] = getRole(dr.GetInt32(1));
            }
            //Session["UserRole"] = getRole(ID);
            dr.Close();
        }
        catch (SqlException ex)
        {
            return ex.Message;
        }
        return SSTCryptographer.Decrypt(TmpPass, System.Web.Configuration.WebConfigurationManager.AppSettings["KEY"]);
    }
    private string getRole(Int32 UserID)
    {
        cmd = new SqlCommand("Select Role from HAT_UserRoles where UserID=@ID", conn);
        cmd.Parameters.Add("@ID", SqlDbType.Int).Value = UserID;
        try
        {
            if (!dr.IsClosed)
                dr.Close();
            dr = cmd.ExecuteReader();
            while (dr.Read())
            {
                return dr.GetString(0);
            }
            dr.Close();
        }
        catch (SqlException ex)
        {
            return ex.Message;
        }
        return string.Empty;
    }
    protected void LoginControl_LoginError(object sender, EventArgs e)
    {
        ltMessage.Text = "Login Error. Try again after some time!";
    }
}